package app

import (
    "os/signal"
    "os"
    "syscall"
    "encoding/json"

    "git.edaijia-inc.cn/edaijia/ego/efree_demo/service"
    pb "git.edaijia-inc.cn/edaijia/ego/efree_demo/proto"

    "git.edaijia-inc.cn/edaijia/ego/elogger"
    "git.edaijia-inc.cn/edaijia/ego/erpc/rpcserver"
    "git.edaijia-inc.cn/edaijia/ego/erpc/apiproxy"

    "golang.org/x/net/context"
    "google.golang.org/grpc"
    "github.com/grpc-ecosystem/grpc-gateway/runtime"
)

type App struct {
    AppRpcServer *rpcserver.RpcServer
    AppApiProxyServer *apiproxy.ApiProxyServer
}

func NewApp() *App {
    gConfig := InitConfig()
    elogger.InitELogger(gConfig.Log)

    rpcServer, err := rpcserver.NewRpcServer(
        gConfig.RPCAddr,
        func(grpcServer *grpc.Server) error {
            pb.RegisterEfreeDemoServer(grpcServer, &service.EfreeDemoService{})
            return nil
        },
    )
    if err != nil {
        elogger.Panicf("serve: %v\n", err)
        return nil
    }

    apiProxyServer, err := apiproxy.NewApiProxyServer(
        gConfig.ProxyAddr,
        func(muxHttpServer *runtime.ServeMux) error {
            opts := []grpc.DialOption{grpc.WithInsecure()}
            pb.RegisterEfreeDemoHandlerFromEndpoint(context.Background(), muxHttpServer, gConfig.RPCAddr, opts)
            return nil
        },
    )
    if err != nil {
        elogger.Panicf("serve: %v\n", err)
        return nil
    }

    confJson, _ := json.Marshal(gConfig)
    elogger.Infof("server config, %s", string(confJson))

    return &App{rpcServer, apiProxyServer}
}

func (e *App) Serve() {
    e.AppRpcServer.Run(false)
    e.AppApiProxyServer.Run(false)

    sigs := make(chan os.Signal,1)
    signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
    elogger.Infof("server running, rpc addr: %s, api addr: %s", GetGConfig().RPCAddr, GetGConfig().ProxyAddr)
    <-sigs
    elogger.Info("server stop")
}
